package com.imitationsql.web.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.imitationsql.web.domain.MenuMetaData;
import com.imitationsql.web.entity.MenuEntity;
import com.imitationsql.web.service.JdbcService;
import com.imitationsql.web.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>Description: some description </p>
 *
 * @author : xiaodong.yang
 * @date : 2024/4/12 17:43
 */
@Service
public class MenuServiceImpl implements MenuService {

    @Autowired
    private JdbcService jdbcService;

    @Override
    public List<MenuMetaData> tree() {
        List<MenuMetaData> dataList = new ArrayList<>();
        List<MenuEntity> list = jdbcService.list(MenuEntity.class, new MenuEntity());
        if (CollUtil.isEmpty(list)) {
            return dataList;
        }
        Map<Serializable, List<MenuEntity>> map = list.stream().filter(item -> item.getParentId() != null).collect(Collectors.groupingBy(MenuEntity::getParentId));

        List<MenuEntity> parentList = list.stream().filter(item -> item.getParentId() == null).collect(Collectors.toList());
        for (MenuEntity menuEntity : parentList) {
            MenuMetaData menuMetaData = new MenuMetaData();
            menuMetaData.setName(menuEntity.getMenuName());
            menuMetaData.setPath(menuEntity.getRouteUrl());
            menuMetaData.setChildren(getChildren(map, menuEntity));
            dataList.add(menuMetaData);
        }
        return dataList;
    }

    private List<MenuMetaData> getChildren(Map<Serializable, List<MenuEntity>> map, MenuEntity menuEntity) {
        List<MenuMetaData> dataList = new ArrayList<>();
        Serializable id = menuEntity.getId();
        List<MenuEntity> children = map.get(id);
        if (CollUtil.isEmpty(children)) {
            return dataList;
        }
        for (MenuEntity child : children) {
            MenuMetaData menuMetaData = new MenuMetaData();
            menuMetaData.setName(child.getMenuName());
            menuMetaData.setPath(child.getRouteUrl());
            menuMetaData.setChildren(getChildren(map, child));
            dataList.add(menuMetaData);
        }
        return dataList;
    }
}
